package com.pinion.controller.business;

import com.base.config.Constant;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;
import com.pinion.export.ExportFailureGoods;
import com.pinion.model.*;
import com.pinion.model.log.T_Error_Info_log;
import com.pinion.util.ExportExcel;
import com.pinion.util.ImportExcel;
import com.pinion.util.ZipUtil;
import com.zh_new.annotation.RouteBind;
import com.zh_new.controller.BaseController;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

@RouteBind(path = "/Main/Goods", viewPath = "/Business/Goods")
public class GoodsController extends BaseController {

    private static final Logger log = Logger.getLogger(GoodsController.class);

    private String navTabId = "Goods";
    private String regionCodeNavTabId = "RegionCode";
    private String regionPriceNavTabId = "RegionPrice";
    private String goodsPictureViewNavTabId = "GoodsPictureView";
    private String specialPictureViewNavTabId = "SpecialPictureView";

    String webRoot = PathKit.getWebRootPath().replace(File.separator, "/");
    String saveDirectory = "goods";
    String newFileName = System.currentTimeMillis() + "";
    private int maxPostSize = Constant.MAX_POST_SIZE;

    /**
     * 商品主页
     */
    public void main() {
        int pageSize = Constant.PAGE_SIZE;
        int pageNumber = 1;
        Integer type = getParaToInt("type");
        Integer brand = getParaToInt("brand");
        try {
            if (null != getPara("numPerPage") && !"".equals(getPara("numPerPage").trim())) {
                pageSize = getParaToInt("numPerPage");
            }
            if (pageSize <= 0) {
                throw new Exception("pageSize不能小于0！");
            }
            if (null != getPara("pageNum") && !"".equals(getPara("pageNum").trim())) {
                pageNumber = getParaToInt("pageNum");
            }
            if (pageNumber <= 0) {
                throw new Exception("pageNumber不能小于0！");
            }
        } catch (Exception e) {
            log.error("您提交的查询参数有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的查询参数有误，请检查后重新提交！", "", "", "", "");
            return;
        }

        try {
            setAttr("page", T_Goods.dao.page(pageSize, pageNumber, type, brand));
            setAttr("type", type);
            setAttr("brand", brand);
            setAttr("types", T_Goods_Type.dao.list());
            setAttr("brands", T_Brand.dao.list());
            render("main.jsp");
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "服务器存在错误，数据读取失败！", "", "", "", "");
        }
    }

    /**
     * 商品添加页面
     */
    public void addip() {
        setAttr("types", T_Goods_Type.dao.list());
        setAttr("brands", T_Brand.dao.list());
        render("add.jsp");
    }


    /**
     * 商品添加处理
     */
    public void add() {
        if (null == getPara("t_Goods.number") || 0 == getPara("t_Goods.number").trim().length()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        List<T_Goods> list = T_Goods.dao.list(getPara("t_Goods.number"));
        if (null != list && 0 < list.size()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品编号已经存在，不能重复！", "", "", "", "");
            return;
        }
        T_Goods model = getModel(T_Goods.class);
        Integer typeId = model.getInt("type_id");
        if (null != typeId) {
            T_Goods_Type brand = T_Goods_Type.dao.findById(typeId);
            if (null != brand) {
                model.set("type_name", brand.getStr("name"));
                model.set("type_number", brand.getStr("number"));
            }
        } else {
            toDwzJson(Constant.STATUS_CODE_ERROR, "商品类型不存在，请检查后重新提交！", "", "", "", "");
        }
        Integer brandId = model.getInt("brand_id");
        if (null != brandId) {
            T_Brand brand = T_Brand.dao.findById(brandId);
            if (null != brand) {
                model.set("brand", brand.getStr("name"));
                model.set("barnd_number", brand.getStr("number"));
            }
        } else {
            toDwzJson(Constant.STATUS_CODE_ERROR, "商品品牌不存在，请检查后重新提交！", "", "", "", "");
        }
        try {
            if (model.save()) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品添加完成！", navTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }


    /**
     * 商品修改页面
     */
    public void updateip() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods model = T_Goods.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品不存在！", "", "", "", "");
            return;
        }
        setAttr("t_Goods", model);
        setAttr("types", T_Goods_Type.dao.list());
        setAttr("brands", T_Brand.dao.list());
        render("update.jsp");
    }

    /**
     * 商品修改处理
     */
    public void update() {
        Integer id;
        try {
            id = getParaToInt("t_Goods.id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods goods = T_Goods.dao.findById(id);
        if (null == goods) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品不存在！", "", "", "", "");
            return;
        }
        if (!goods.getStr("number").equals(getPara("t_Goods.number"))) {
            List<T_Goods> list = T_Goods.dao.list(id, getPara("t_Goods.number"));
            if (null != list && 0 < list.size()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品编号已经存在，不能重复！", "", "", "", "");
                return;
            }
        }
        T_Goods model = getModel(T_Goods.class);
        Integer typeId = model.getInt("type_id");
        if (null != typeId) {
            T_Goods_Type brand = T_Goods_Type.dao.findById(typeId);
            if (null != brand) {
                model.set("type_name", brand.getStr("name"));
                model.set("type_number", brand.getStr("number"));
            }
        } else {
            toDwzJson(Constant.STATUS_CODE_ERROR, "商品类型不存在，请检查后重新提交！", "", "", "", "");
        }
        Integer brandId = model.getInt("brand_id");
        if (null != brandId) {
            T_Brand brand = T_Brand.dao.findById(brandId);
            if (null != brand) {
                model.set("brand", brand.getStr("name"));
                model.set("brand_number", brand.getStr("number"));
            }
        } else {
            toDwzJson(Constant.STATUS_CODE_ERROR, "商品品牌不存在，请检查后重新提交！", "", "", "", "");
        }
        try {
            if (model.update()) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品修改完成！", navTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 商品删除处理
     */
    public void delete() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods model = T_Goods.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品不存在！", "", "", "", "");
            return;
        }
        //TODO 统计order item里面对商品的引用次数
        Long count = 0L;
        if (count > 0) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "商品已经被引用，不能删除！", "", "", "", "");
            return;
        }
        try {
            if (model.delete()) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品删除完成！", navTabId, "", "", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }


    /**
     * 上传文件
     */
    @ClearInterceptor(ClearLayer.ALL)
    public void uploadFile() {
        uploadFile("file");
    }

    @ClearInterceptor(ClearLayer.ALL)
    public void uploadImage() {
        uploadFile("image");
    }

    public void uploadFlash() {
        uploadFile("flash");
    }

    @ClearInterceptor(ClearLayer.ALL)
    public void uploadMedia() {
        uploadFile("media");
    }

    public void uploadFile(String fileType) {
        try {
            UploadFile file = getFile("filedata", saveDirectory);
            newFileName += file.getFileName().substring(file.getFileName().lastIndexOf("."), file.getFileName().length());
            saveDirectory = saveDirectory + "/" + fileType;
            file.getFile().renameTo(new File(webRoot + "/" + saveDirectory + "/" + newFileName));
        } catch (Exception e) {
            log.error("上传图片出错，请检查后再提交！", e);
            render(new JsonRender("{\"err\":\"上传图片出错，请检查后再提交！\",\"msg\":\"\"}").forIE());
        }
        render(new JsonRender("{\"err\":\"\",\"msg\":\"" + saveDirectory + "/" + newFileName + "\"}").forIE());
    }

    /**
     * 进入批量添加页面
     */
    public void batchAddGoodsip() {
        render("batchAdd.jsp");
    }

    /**
     * 批量添加商品处理
     */
    public void batchAddGoods() {
        try {
            //读取excel
            List<T_Goods> goodsList = new ArrayList<T_Goods>();
            List failList = new ArrayList<List<String>>();
            List<List<String>> originalDataList = new ArrayList<List<String>>();
            goodsList = read(originalDataList, failList);
            int i = 0;
            for (int j = 0; j < goodsList.size(); j++) {
                T_Goods o = goodsList.get(j);
                String number = o.getStr("number");
                if (StrKit.notBlank(number)) {
                    T_Goods goods = T_Goods.dao.getByNumber(number);
                    List<String> originalRow = originalDataList.get(j);
                    if (null != goods) {
                        //已存在相同编号的商品，打错误日志，返回excel文件，文件里包含未成功导入的数据和失败原因
                        originalRow.add("已存在相同编号的商品! ");
                        failList.add(originalRow);
                        log.error("已存在相同编号的商品,商品信息导入失败! 商品编号为：" + number);
                        continue;
                    } else {
                        String errorMsg = "";
                        try {
                            if (o.getStr("description").length() > 255) {
                                errorMsg += "商品简介长度不能大于255! ,";
                            }
                            if (o.getStr("model").length() > 255) {
                                errorMsg += "商品型号长度不能大于255! ,";
                            }
                            if (o.getStr("parameter").length() > 255) {
                                errorMsg += "参数长度不能大于255! ,";
                            }
                            if (o.getDouble("price") < 0 || o.getDouble("price") > 999999999.0) {
                                errorMsg += "标价不能小于零且不能大于999999999! ,";
                            }
                            if (o.getDouble("cost_price") < 0 || o.getDouble("cost_price") > 999999999.0) {
                                errorMsg += "成本价不能小于零且不能大于999999999! ,";
                            }
                            if (o.getDouble("commission") < 0 || o.getDouble("commission") > 99999.0) {
                                errorMsg += "提成百分比不能小于零且不能大于99999! ,";
                            }
                            if (o.getInt("stock") < 0 || o.getInt("stock") > 999999999) {
                                errorMsg += "库存量不能小于零且不能大于999999999! ,";
                            }
                            if (o.getStr("name").length() > 255) {
                                errorMsg += "商品名称长度不能大于255! ,";
                            }
                            if (o.getStr("number").length() > 255) {
                                errorMsg += "商品编号长度不能大于255! ,";
                            }
                            if (null == T_Goods_Type.dao.findById(o.getInt("type_id"))) {
                                errorMsg += "商品类型不存在! ,";
                            }

                            T_Brand tb = T_Brand.dao.getByNumber(o.getStr("brand_number"));
                            if (null == tb) {
                                errorMsg += "商品品牌不存在! ,";
                            } else {
                                if (!tb.getStr("name").equals(o.getStr("brand"))) {
                                    errorMsg += "商品品牌名称和商品品牌编号不对应! ,";
                                }
                            }
                        } catch (NumberFormatException e) {
                            log.error("类型转换错误! ", e);
                            errorMsg += "类型转换错误! ,";
                        } catch (Exception e) {
                            log.error("数据处理存在错误! ", e);
                            errorMsg += "数据处理存在错误! ,";
                        }
                        if (!errorMsg.equals("")) {
                            errorMsg = errorMsg.substring(0, errorMsg.length() - 1);
                            originalRow.add(errorMsg);
                            failList.add(originalRow);
                            log.error(errorMsg);
                            continue;
                        }
                    }
                }
                o.save();
                log.info("商品信息导入成功! 商品编号为：" + number);
                i++;
            }
            int failListSize = failList.size();
            if (failListSize > 0 || i == 0) {
                if (i == 0 && failListSize == 0) {
                    renderJson("{\"statusCode\":\"300\", " + "\"message\":\"没有可导入的商品信息！\"}");
                    return;
                } else {
                    HttpServletResponse response = getResponse();
                    response.setHeader("Content-disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
                    response.setContentType("application/octet-stream");
                    try {
                        //OutputStream os = response.getOutputStream();
                        File errorXls = new File(webRoot + "/" + saveDirectory + "/errorfile_" + Constant.ERROR_TYPE_BG + "_" + newFileName + Constant.XLS);
                        if (!errorXls.getParentFile().exists()) {
                            errorXls.getParentFile().mkdir();
                        }
                        errorXls.createNewFile();
                        OutputStream os = new FileOutputStream(errorXls);
                        String title = "未导入成功的商品信息";
                        String[] headers = new String[]{"商品类型名称", "商品类型编号", "商品名称", "商品编号", "商品品牌", "商品品牌编号", "商品型号", "商品简介", "商品参数", "商品标价",
                                "商品成本价", "销售提成(%)", "库存量", "详细介绍", "区域价格", "错误原因"};
                        ExportExcel<List> ex = new ExportFailureGoods();
                        ex.exportExcel(title, headers, failList, os, null);

                        //记录失败信息
                        new T_Error_Info_log().set("err_type", Constant.ERROR_TYPE_BG).set("error_date", new Date()).
                                set("url", saveDirectory + "/errorfile_" + Constant.ERROR_TYPE_BG + "_" + newFileName + Constant.XLS).save();

                        renderFile(errorXls);
                        os.close();
                    } catch (IOException e) {
                        log.error("写入xls文件出错！");
                    }
                }
            } else {
                toDwzJson(Constant.STATUS_CODE_OK, "商品信息导入完成！共导入" + i + "条商品信息。", navTabId, "", "closeCurrent", "");
            }
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            renderJson("{\"statusCode\":\"300\", " + "\"message\":\"服务器存在错误，数据读取失败！\"}");
        }
    }

    /**
     * 进入批量修改页面
     */
    public void batchUpdateGoodsip() {
        render("batchUpdate.jsp");
    }

    /**
     * 批量修改商品处理
     */
    public void batchUpdateGoods() {
        try {
            //读取excel
            List<T_Goods> goodsList = new ArrayList<T_Goods>();
            List failList = new ArrayList<List<String>>();
            List<List<String>> originalDataList = new ArrayList<List<String>>();
            goodsList = read(originalDataList, new ArrayList<List<String>>());
            int i = 0;
            for (int j = 0; j < goodsList.size(); j++) {
                T_Goods o = goodsList.get(i);
                String number = o.getStr("number");
                if (StrKit.notBlank(number)) {
                    T_Goods goods = T_Goods.dao.getByNumber(number);
                    if (null != goods) {
                        int id = goods.getInt("id");
                        int pictureCount = goods.getInt("picture_count");
                        goods = o;
                        goods.set("id", id);
                        goods.set("picture_count", pictureCount);
                        goods.update();
                        log.info("商品信息修改成功! 商品编号为：" + number);
                        i++;
                    } else {
                        //不存在的商品编号，打错误日志，返回excel文件，文件里包含未成功修改的数据和失败原因
                        List<String> originalRow = originalDataList.get(j);
                        originalRow.add("不存在此商品编号对应的商品，无法修改商品信息！ ");
                        failList.add(originalRow);
                        log.error("不存在此商品编号对应的商品，无法修改商品信息！商品编号为：" + number);
                        continue;
                    }
                }
            }

            int failListSize = failList.size();
            if (failListSize > 0 || i == 0) {
                if (i == 0 && failListSize == 0) {
                    renderJson("{\"statusCode\":\"300\", " + "\"message\":\"没有可导入的商品信息！\"}");
                    return;
                } else {
                    HttpServletResponse response = getResponse();
                    response.setHeader("Content-disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
                    response.setContentType("application/octet-stream");
                    try {
                        OutputStream os = response.getOutputStream();
                        String title = "未修改成功的商品信息";
                        String[] headers = new String[]{"商品类型名称", "商品类型编号", "商品名称", "商品编号", "商品品牌", "商品品牌编号", "商品型号", "商品简介", "商品参数", "商品标价",
                                "商品成本价", "销售提成(%)", "库存量", "详细介绍", "错误原因"};
                        ExportExcel<List> ex = new ExportFailureGoods();
                        ex.exportExcel(title, headers, failList, os, null);
                        renderNull();
                        os.close();
                    } catch (IOException e) {
                        log.error("解析xls文件出错，数据读取失败！", e);
                    }
                }
            } else {
                toDwzJson(Constant.STATUS_CODE_OK, "商品信息修改完成！共修改" + i + "条商品信息。", navTabId, "", "closeCurrent", "");
            }
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            renderJson("{\"statusCode\":\"300\", \"message\":\"服务器存在错误，数据读取失败！\"}");
        }
    }

    /**
     * 进入批量删除页面
     */
    public void batchDeleteGoodsip() {
        render("batchDelete.jsp");
    }

    /**
     * 批量删除商品处理
     */
    public void batchDeleteGoods() {
        try {
            //读取excel
            List<T_Goods> goodsList = new ArrayList<T_Goods>();
            List failList = new ArrayList<List<String>>();
            List<List<String>> originalDataList = new ArrayList<List<String>>();
            goodsList = read(originalDataList, new ArrayList<List<String>>());
            int i = 0;
            for (int j = 0; j < goodsList.size(); j++) {
                T_Goods o = goodsList.get(i);
                String number = o.getStr("number");
                if (StrKit.notBlank(number)) {
                    T_Goods goods = T_Goods.dao.getByNumber(number);
                    if (null != goods) {
                        int id = goods.getInt("id");
                        int pictureCount = goods.getInt("picture_count");
                        goods = o;
                        goods.set("id", id);
                        goods.set("picture_count", pictureCount);
                        goods.update();
                        log.info("商品信息已成功删除! 商品编号为：" + number);
                        i++;
                    } else {
                        //TODO 不存在的商品编号，打错误日志，返回excel文件，文件里包含未成功修改的数据和失败原因
                        List<String> originalRow = originalDataList.get(j);
                        originalRow.add("不存在此商品编号对应的商品，无法删除商品信息！ ");
                        failList.add(originalRow);
                        log.error("不存在此商品编号对应的商品，无法删除商品信息！商品编号为：" + number);
                        continue;
                    }
                }
            }

            int failListSize = failList.size();
            if (failListSize > 0 || i == 0) {
                if (i == 0 && failListSize == 0) {
                    renderJson("{\"statusCode\":\"300\", " + "\"message\":\"没有可导入的商品信息！\"}");
                    return;
                } else {
                    HttpServletResponse response = getResponse();
                    response.setHeader("Content-disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
                    response.setContentType("application/octet-stream");
                    try {
                        OutputStream os = response.getOutputStream();
                        String title = "未删除成功的商品信息";
                        String[] headers = new String[]{"商品类型名称", "商品类型编号", "商品名称", "商品编号", "商品品牌", "商品品牌编号", "商品型号", "商品简介", "商品参数", "商品标价",
                                "商品成本价", "销售提成(%)", "库存量", "详细介绍", "错误原因"};
                        ExportExcel<List> ex = new ExportFailureGoods();
                        ex.exportExcel(title, headers, failList, os, null);
                        renderNull();
                        os.close();
                    } catch (IOException e) {
                        log.error("写入xls文件出错！", e);
                    }
                }
            } else {
                toDwzJson(Constant.STATUS_CODE_OK, "商品信息删除完成！共删除" + i + "条商品信息。", navTabId, "", "closeCurrent", "");
            }
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            renderJson("{\"statusCode\":\"300\", " + "\"message\":\"服务器存在错误，数据读取失败！\"}");
        }
    }

    public List<T_Goods> read(List<List<String>> originalDataList, List<List<String>> failList) {
        //上传excel
        UploadFile excelFile = getFile("excel", saveDirectory, maxPostSize);
        String fileName = excelFile.getFileName();
        String filePath = PathKit.getWebRootPath() + "/File/" + saveDirectory + "/" + fileName;
        List<T_Goods> dataList = new ArrayList<T_Goods>();
        InputStream is = null;
        try {
            boolean isExcel2003 = true;
            if (ImportExcel.isExcel2007(filePath)) {
                isExcel2003 = false;
            }
            File file = new File(filePath);
            is = new FileInputStream(file);
            dataList = read(is, isExcel2003, originalDataList, failList);
            is.close();
        } catch (Exception e) {
            log.error("上传文件出错！", e);
        }
        return dataList;
    }

    public List<T_Goods> read(InputStream inputStream, boolean isExcel2003, List<List<String>> originalDataList, List<List<String>> failList) {
        try {
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(inputStream);
            } else {
                wb = new XSSFWorkbook(inputStream);
            }
            return read(wb, originalDataList, failList);
        } catch (IOException e) {
            log.error("读取文件出错！", e);
        }
        return null;
    }

    private List<T_Goods> read(Workbook wb, List<List<String>> originalDataList, List<List<String>> failList) {
        org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);
        Integer totalRows = sheet.getPhysicalNumberOfRows();
        Integer totalCells = 0;
        //有数据才读
        if (totalRows >= 3 && sheet.getRow(2) != null) {
            totalCells = sheet.getRow(1).getPhysicalNumberOfCells();
        }
        if (totalCells >= 1) {
            return readGoods(sheet, originalDataList, failList);
        }
        return null;
    }

    public List<T_Goods> readGoods(org.apache.poi.ss.usermodel.Sheet st, List<List<String>> originalDataList, List<List<String>> failList) {
        List<T_Goods> goodsList = new ArrayList<T_Goods>();
        int totalRow = st.getPhysicalNumberOfRows();
        originalDataList = getContent(originalDataList, st, 2, totalRow, null);

        String errMsg;  //出错原因
        T_Region_Price rpModel;  //区域价格Model
        String regionPriceStr;  //区域价格字段
        String[] regionPriceArr;   //区域价格字段按照"|"分割后的数据
        Map<String, Double> regionPriceMap;  //区域价格字段Map

        for (int i = 0; i < originalDataList.size(); i++) {
            List<String> content = originalDataList.get(i);
            T_Goods o = new T_Goods();

            //商品类型处理，不存在的类型就加入数据库
            String goodsTypeNumber = content.get(1).trim();
            String goodsTypeName = content.get(0).trim();
            if (StrKit.notBlank(goodsTypeNumber)) {
                T_Goods_Type goodsType = T_Goods_Type.dao.getByNumber(goodsTypeNumber);
                if (null != goodsType) {
                    o.set("type_id", goodsType.getInt("id"));
                } else {
                    goodsType = getModel(T_Goods_Type.class);
                    goodsType.set("number", goodsTypeNumber);
                    if (StrKit.notBlank(goodsTypeName)) {
                        goodsType.set("name", goodsTypeName);
                    } else {
                        goodsType.set("name", goodsTypeNumber);
                    }
                    goodsType.save();
                    o.set("type_id", goodsType.getInt("id"));
                    log.info("系统新增商品类型，类型ID：" + goodsType.getInt("id") + "类型名：" + goodsType.getStr("name") + "类型编号：" + goodsType.getStr("number"));
                }
            }

            o.set("type_name", goodsTypeName);
            o.set("type_number", goodsTypeNumber);
            o.set("name", content.get(2).trim());
            o.set("number", content.get(3).trim());

            //商品品牌处理，不存在的品牌就加入数据库
            String goodsBrandNumber = content.get(5).trim();
            String goodsBrandName = content.get(4).trim();
            if (StrKit.notBlank(goodsBrandNumber)) {
                T_Brand brand = T_Brand.dao.getByNumber(goodsBrandNumber);
                if (null != brand) {
                    o.set("brand_id", brand.getInt("id"));
                } else {
                    brand = getModel(T_Brand.class);
                    brand.set("number", goodsBrandNumber);
                    if (StrKit.notBlank(goodsBrandName)) {
                        brand.set("name", goodsBrandName);
                    } else {
                        brand.set("name", goodsBrandNumber);
                    }
                    brand.save();
                    o.set("brand_id", brand.getInt("id"));
                    log.info("系统新增商品品牌，品牌ID：" + brand.getInt("id") + "品牌名：" + brand.getStr("name") + "品牌编号：" + brand.getStr("number"));
                }
            }

            o.set("brand", goodsBrandName);
            o.set("brand_number", goodsBrandNumber);
            o.set("model", content.get(6).trim());
            o.set("description", content.get(7).trim());
            o.set("parameter", content.get(8).trim());
            String priceStr = content.get(9).trim();
            if (StrKit.notBlank(priceStr)) {
                try {
                    Double price = Double.valueOf(priceStr);
                    o.set("price", price);
                } catch (Exception e) {
                    log.error("价格数据格式有问题[价格转化为Double类型时出错]！", e);
                    content.add("价格数据格式有问题[价格转化为Double类型时出错]！");
                    failList.add(content);
                    continue;
                }
            }
            String costPriceStr = content.get(10).trim();
            if (StrKit.notBlank(costPriceStr)) {
                try {
                    Double costPrice = Double.valueOf(costPriceStr);
                    o.set("cost_price", costPrice);
                } catch (Exception e) {
                    log.error("成本价格数据格式有问题[成本价格转化为Double类型时出错]！", e);
                    content.add("成本价格数据格式有问题[成本价格转化为Double类型时出错]！");
                    failList.add(content);
                    continue;
                }
            }
            String commissionStr = content.get(11).trim();
            if (StrKit.notBlank(commissionStr)) {
                try {
                    Double commission = Double.valueOf(commissionStr);
                    o.set("commission", commission);
                } catch (Exception e) {
                    log.error("提成百分比数据格式有问题[提成百分比转化为Double类型时出错]！", e);
                    content.add("提成百分比数据格式有问题[提成百分比转化为Double类型时出错]！");
                    failList.add(content);
                    continue;
                }
            }
            String stockStr = content.get(12).trim();
            if (StrKit.notBlank(stockStr)) {
                try {
                    Integer stock = Integer.valueOf(stockStr);
                    o.set("stock", stock);
                } catch (Exception e) {
                    log.error("库存量数据格式有问题[库存量转化为Double类型时出错]！", e);
                    content.add("库存量数据格式有问题[库存量转化为Double类型时出错]！");
                    failList.add(content);
                    continue;
                }
            }
            o.set("detail", content.get(13).trim());

            /* add -- 处理excel中的区域价格字段 -- date:2015.6.1 -- begin */
            regionPriceStr = content.get(14);
            if (null != regionPriceStr) {
                regionPriceArr = regionPriceStr.trim().split("\\|");
                if (0 == regionPriceArr.length % 2) {
                    regionPriceMap = new HashMap<String, Double>();
                    for (int idx = 0; idx < regionPriceArr.length / 2; idx++) {
                        //将"区域码"和"区域价格"放入regionPriceMap
                        try {
                            regionPriceMap.put(regionPriceArr[idx * 2].trim(), Double.valueOf(regionPriceArr[idx * 2 + 1].trim()));
                            //将数据录入T_Region_Price表中
                            rpModel = new T_Region_Price();
                            rpModel.set("goods_number", content.get(3).trim()); //商品编号
                            rpModel.set("r_code", regionPriceArr[idx * 2].trim());  //区域码
                            rpModel.set("price", Double.valueOf(regionPriceArr[idx * 2 + 1].trim())); //区域价格
                            rpModel.save();
                        } catch (NumberFormatException nfe) {
                            errMsg = "区域价格数据格式有问题[区域价格转化为Double类型时出错]！";
                            log.error(errMsg);
                            //将此条数据插入failList中
                            content.add(errMsg);
                            failList.add(content);
                            continue;
                        }
                    }
                } else {
                    errMsg = "读入区域价格字段异常[缺少区域码或区域价格]!";
                    log.error(errMsg);
                    //将此条数据插入failList中
                    content.add(errMsg);
                    failList.add(content);
                    continue;
                }
            }
            /* add -- 处理excel中的区域价格字段 -- date:2015.6.1 -- end */

            goodsList.add(o);

        }
        return goodsList;
    }

    public List<List<String>> getContent(List<List<String>> originalDataList, org.apache.poi.ss.usermodel.Sheet st, int rowStart, int rowTotal, Long date) {
        int totalCol = st.getRow(1).getPhysicalNumberOfCells();
        for (int r = rowStart; r < rowTotal; r++) {
            List<String> content = new ArrayList<String>();
            Row row = st.getRow(r);
            for (int col = 0; col < totalCol; col++) {
                String cellValue = "";
                Cell cell = row.getCell(col);
                if (null != cell) {
                    switch (cell.getCellType()) {
                        case HSSFCell.CELL_TYPE_BLANK:  //空值
                            cellValue = "";
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                            long longVal = Math.round(cell.getNumericCellValue());
                            if (Double.parseDouble(longVal + ".0") == cell.getNumericCellValue()) {       //整型
                                cellValue = String.valueOf(longVal);
                            } else {         //double型
                                cellValue = cell.getStringCellValue();
                            }
                            break;
                        default:
                            cellValue = cell.getStringCellValue();
                            break;
                    }
                }
//                String cellValue = null == row.getCell(col) ? "" : row.getCell(col).toString();
                content.add(cellValue);
            }
            originalDataList.add(content);
        }
        return originalDataList;
    }


    /**
     * 进入批量上传图片ZIP包页面
     */
    public void batchImageUploadip() {
        render("batchImageUpload.jsp");
    }

    //上传图片ZIP包
    public void batchImageUpload() throws IOException {
        //IP包文件落地
        UploadFile imagesZipFile = getFile("imagezip", Constant.UPLOAD_IMAGESZIP_PATH, Constant.MAX_IMAGES_UPLOAD_SIZE);
        String fileName = imagesZipFile.getFileName();
        //判断是不是zip包
        if (!"zip".equals(fileName.substring(fileName.indexOf(".") + 1).toLowerCase())) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您上传的文件不是ZIP压缩包,请上传正确的文件！", "", "", "", "");
            return;
        }

        List<String> errorInfo = new ArrayList<String>();

//        //创建解压临时目录
//        String decompressPath = Constant.UPLOAD_IMAGESZIP_PATH + new SimpleDateFormat("yyyyMMDDHHmmss").format(new Date());
//        File decompressDir = new File(decompressPath);
//        if (decompressDir.exists()) {
//            log.error("创建目录" + decompressPath + "失败，目标目录已经存在");
//            toDwzJson(Constant.STATUS_CODE_ERROR, "您上传的文件名重复,请修改后上传！", "", "", "", "");
//            return;
//        }
//        if (!decompressPath.endsWith(File.separator)) {
//            decompressPath = decompressPath + File.separator;
//        }
//        if (!decompressDir.mkdirs()) {
//            log.error("创建目录" + decompressPath + "失败！");
//            toDwzJson(Constant.STATUS_CODE_ERROR, "创建目录" + decompressPath + "失败！请修改后重新上传！", "", "", "", "");
//            return;
//        }
//        log.error("创建目录" + decompressPath + "成功！");

        //解压ZIP包
        List<String> fileList = ZipUtil.decompress(Constant.UPLOAD_IMAGESZIP_PATH + fileName, Constant.UPLOAD_IMAGESZIP_PATH, "UTF-8");
        if (null == fileList || fileList.size() < 1) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "上传的ZIP包中没有文件!", "", "", "", "");
            return;
        }

        List<String> failImgNameList = new ArrayList<String>();
        //处理图片
        File decompressDir = new File(Constant.UPLOAD_IMAGESZIP_PATH + fileList.get(0));
        decompressDir = decompressDir.getParentFile();
        for (File f : decompressDir.listFiles()) {
//        for (String fn : fileList) {
            String fn = f.getName();
            //验证图片名称
            String suffix = fn.substring(fn.indexOf(".") + 1).toLowerCase().trim();
            if (!"jpg".equals(suffix) && !"png".equals(suffix) && !"bmp".equals(suffix)) {
                failImgNameList.add(fn);
                log.error(fn + "--图片文件后缀不为系统可识别的后缀");
                errorInfo.add("{" + fn + "}\t{图片文件后缀不为系统可识别的后缀}");
                continue;
            }
            //解析文件名
            String prefix = fn.substring(0, fn.indexOf("."));
            String[] prefixArr = prefix.split("_");
            if (prefixArr.length != 3) {
                failImgNameList.add(fn);
                log.error(prefix + "--图片文件前缀不合法");
                errorInfo.add("{" + fn + "}\t{" + prefix + "--图片文件前缀不合法}");
                continue;
            }
            //检查图片对应的商品是否存在
            Record goodsRecord = Db.findFirst("SELECT * FROM t_goods WHERE number=?", prefixArr[0]);
            if (null == goodsRecord) {
                failImgNameList.add(fn);
                log.error(prefix + "--图片对应的商品不存在");
                errorInfo.add("{" + fn + "}\t{" + prefix + "--图片对应的商品不存在}");
                continue;
            }
            //检查图片类型
            if (!"zs".equals(prefixArr[1]) && !"xq".equals(prefixArr[1]) && !"cs".equals(prefixArr[1]) && !"tj".equals(prefixArr[1]) && !"rd".equals(prefixArr[1])) {
                failImgNameList.add(fn);
                log.error(prefix + "--图片类型不合法");
                errorInfo.add("{" + fn + "}\t{" + prefix + "--图片类型不合法}");
                continue;
            }
            //检查图片名是否重复
            T_Goods_Picture gPic = new T_Goods_Picture().getByName(prefix);
            if (null == gPic) {
                gPic = new T_Goods_Picture();
                gPic.set("goods_number", prefixArr[0]);
                gPic.set("url", f.getPath());
                gPic.set("pic_name", prefix);
                gPic.set("pic_type", prefixArr[1]);
                gPic.set("pic_index", prefixArr[2]);
                gPic.save();
            } else {
                gPic.set("goods_number", prefixArr[0]);
                gPic.set("url", f.getPath());
                gPic.set("pic_name", prefix);
                gPic.set("pic_type", prefixArr[1]);
                gPic.set("pic_index", prefixArr[2]);
                gPic.update();
            }

        }

        //记录错误信息
        File errorTxt = new File(webRoot + "/" + saveDirectory + "/errorfile_" + Constant.ERROR_TYPE_BI + "_" + newFileName + Constant.TXT);
        if (!errorTxt.getParentFile().exists()) {
            errorTxt.getParentFile().mkdir();
        }
        errorTxt.createNewFile();

        BufferedWriter writer = new BufferedWriter(new FileWriter(errorTxt, true));
        for (String error : errorInfo) {
            writer.write(error);
        }
        writer.close();

        //记录失败信息
        new T_Error_Info_log().set("err_type", Constant.ERROR_TYPE_BI).set("error_date", new Date()).
                set("url", saveDirectory + "/errorfile_" + Constant.ERROR_TYPE_BI + "_" + newFileName + Constant.TXT).save();
    }

    /**
     * 区域价格主页
     */
    public void regionPrice() {
        String select = "SELECT *";
        int pageSize = Constant.PAGE_SIZE;
        int pageNumber = 1;
        try {
            if (null != getPara("numPerPage") && !"".equals(getPara("numPerPage").trim())) {
                pageSize = getParaToInt("numPerPage");
            }
            if (pageSize <= 0) {
                throw new Exception();
            }
            if (null != getPara("pageNum") && !"".equals(getPara("pageNum").trim())) {
                pageNumber = getParaToInt("pageNum");
            }
            if (pageNumber <= 0) {
                throw new Exception();
            }
        } catch (Exception e) {
            log.error("您提交的查询参数有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的查询参数有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        String sqlExceptSelect = "FROM t_region_price";
        try {
            Page<T_Region_Price> page = T_Region_Price.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
            setAttr("page", page);
            render("regionPrice.jsp");
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "服务器存在错误，数据读取失败！", "", "", "", "");
        }
    }

    /**
     * 区域价格添加页面
     */
    public void regionPaddip() {
        setAttr("goodses", T_Goods.dao.list());
        setAttr("regionCodes", T_Region_Code.dao.list());
        render("regionPadd.jsp");
    }

    /**
     * 区域价格添加处理
     */
    public void regionPadd() {
        if (null == getPara("t_Region_Price.goods_number") || 0 == getPara("t_Region_Price.goods_number").trim().length()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        if (null == getPara("t_Region_Price.r_code") || 0 == getPara("t_Region_Price.r_code").trim().length()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        List<T_Region_Price> priceList = T_Region_Price.dao.getByNumAndCode(getParaToInt("t_Region_Price.goods_number"), getPara("t_Region_Price.r_code"));
        if (null != priceList && priceList.size() > 0) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，品牌编号已经存在，不能重复！", "", "", "", "");
            return;
        }
        try {
            if (getModel(T_Region_Price.class).save()) {
                toDwzJson(Constant.STATUS_CODE_OK, "区域价格添加完成！", regionPriceNavTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 区域价格修改页面
     */
    public void regionPupdateip() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Region_Price model = T_Region_Price.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，区域价格不存在！", "", "", "", "");
            return;
        }
        setAttr("t_Region_Price", model);
        setAttr("goodses", T_Goods.dao.list());
        setAttr("regionCodes", T_Region_Code.dao.list());
        render("regionPupdate.jsp");
    }

    /**
     * 区域价格修改处理
     */
    public void regionPupdate() {
        Integer id;
        try {
            id = getParaToInt("t_Region_Price.id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        final T_Region_Price model = T_Region_Price.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，区域价格不存在！", "", "", "", "");
            return;
        }
        if (!model.getStr("r_code").equals(getPara("t_Region_Price.r_code"))) {
            List<T_Region_Price> list = T_Region_Price.dao.getByNumAndCode(getParaToInt("t_Region_Price.goods_number"), getPara("t_Region_Price.r_code"));
            if (null != list && 0 < list.size()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，区域价格已经存在，不能重复！", "", "", "", "");
                return;
            }
        }
        try {
            final T_Region_Price price = getModel(T_Region_Price.class);
            Boolean succeed = price.update();
            if (succeed) {
                toDwzJson(Constant.STATUS_CODE_OK, "区域价格修改完成！", regionPriceNavTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 区域价格删除处理
     */
    public void regionPdelete() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Region_Price model = T_Region_Price.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，区域编码不存在！", "", "", "", "");
            return;
        }
        model.set("is_delete", "1");
        try {
            if (model.update()) {
                toDwzJson(Constant.STATUS_CODE_OK, "区域编码删除完成！", regionPriceNavTabId, "", "", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    //=========================================================================================================

    /**
     * 区域编码主页
     */
    public void regionCode() {
        String select = "SELECT *";
        int pageSize = Constant.PAGE_SIZE;
        int pageNumber = 1;
        try {
            if (null != getPara("numPerPage") && !"".equals(getPara("numPerPage").trim())) {
                pageSize = getParaToInt("numPerPage");
            }
            if (pageSize <= 0) {
                throw new Exception();
            }
            if (null != getPara("pageNum") && !"".equals(getPara("pageNum").trim())) {
                pageNumber = getParaToInt("pageNum");
            }
            if (pageNumber <= 0) {
                throw new Exception();
            }
        } catch (Exception e) {
            log.error("您提交的查询参数有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的查询参数有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        String sqlExceptSelect = "FROM t_region_code";
        try {
            Page<T_Region_Code> page = T_Region_Code.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
            setAttr("page", page);
            render("regionCode.jsp");
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "服务器存在错误，数据读取失败！", "", "", "", "");
        }
    }

    /**
     * 区域编码添加页面
     */
    public void regionaddip() {
        render("regionadd.jsp");
    }

    /**
     * 区域编码添加处理
     */
    public void regionadd() {
        if (null == getPara("t_Region_Code.code") || 0 == getPara("t_Region_Code.code").trim().length()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Region_Code code = T_Region_Code.dao.getByCode("t_Region_Code.code");
        if (null != code) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，品牌编号已经存在，不能重复！", "", "", "", "");
            return;
        }
        try {
            if (getModel(T_Region_Code.class).save()) {
                toDwzJson(Constant.STATUS_CODE_OK, "区域编码添加完成！", regionCodeNavTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 区域编码修改页面
     */
    public void regionupdateip() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Region_Code model = T_Region_Code.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，品牌不存在！", "", "", "", "");
            return;
        }
        setAttr("t_Region_Code", model);
        render("regionupdate.jsp");
    }

    /**
     * 区域编码修改处理
     */
    public void regionupdate() {
        Integer id;
        try {
            id = getParaToInt("t_Region_Code.id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        final T_Region_Code model = T_Region_Code.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，区域编码不存在！", "", "", "", "");
            return;
        }
        if (!model.getStr("code").equals(getPara("t_Region_Code.code"))) {
            List<T_Region_Code> list = T_Region_Code.dao.list(id, getPara("t_Region_Code.code"));
            if (null != list && 0 < list.size()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，区域码已经存在，不能重复！", "", "", "", "");
                return;
            }
        }
        try {
            final T_Region_Code code = getModel(T_Region_Code.class);
            Boolean succeed = Db.tx(new IAtom() {
                public boolean run() throws SQLException {
                    boolean value1;
                    boolean value2 = true;
                    if (value1 = code.update()) {
                        if (code.getStr("code").equals(model.getStr("code"))) {
                            value2 = true;
                        } else {
                            //同步区域价格中的r_code
                            value2 = T_Region_Price.dao.updateCode(model.getStr("code"), code.getStr("code"));
                        }
                    }
                    return value1 && value2;
                }
            });
            if (succeed) {
                toDwzJson(Constant.STATUS_CODE_OK, "区域编码修改完成！", regionCodeNavTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 区域编码删除处理
     */
    public void regiondelete() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Region_Code model = T_Region_Code.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，区域编码不存在！", "", "", "", "");
            return;
        }

        Long count = T_Region_Price.dao.countByCode(model.getStr("code"));
        if (count > 0) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "区域编码已经被引用，不能删除！", "", "", "", "");
            return;
        }
        model.set("is_delete", "1");
        try {
            if (model.update()) {
                toDwzJson(Constant.STATUS_CODE_OK, "区域编码删除完成！", regionCodeNavTabId, "", "", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 进入商品图片浏览页面
     */
    public void goodsPictureViewip() {
        String goods_number;
        try {
            goods_number = getPara("goods_number");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        List<T_Goods_Picture> pictureList = T_Goods_Picture.dao.getByGoodNumber(goods_number);

        setAttr("goods_number", goods_number);
        setAttr("pictureList", pictureList);
        render("goodsPictureView.jsp");
    }

    /**
     * 进入上传商品图片页面
     */
    public void goodsPictureUploadip() {
        String goods_number;
        try {
            goods_number = getPara("goods_number");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }

        setAttr("goods_number", goods_number);
        render("goodsPictureUpload.jsp");
    }

    /**
     * 商品图片修改页面
     */
    public void goodsPictureUpdateip() {
        Integer id;
        try {
            id = getParaToInt("id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods_Picture model = T_Goods_Picture.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品图片不存在！", "", "", "", "");
            return;
        }

        setAttr("t_Goods_Picture", model);
        render("goodsPictureUpdate.jsp");
    }

    /**
     * 商品图片修改处理
     */
    public void goodsPictureUpdate() {
        Integer id;
        try {
            id = getParaToInt("t_Goods_Picture.id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        final T_Goods_Picture model = T_Goods_Picture.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品图片不存在！", "", "", "", "");
            return;
        }
        if (!model.getStr("pic_type").equals(getPara("t_Goods_Picture.pic_type"))) {
            Integer newIndex = T_Goods_Picture.dao.getPicNewIndexByPicType(getPara("t_Goods_Picture.pic_type"));
            model.set("pic_type", getPara("t_Goods_Picture.pic_type")).set("pic_index", newIndex);

            //更改本地文件名，url，pic_name
            String pic_name = model.getStr("pic_name");
            String suffix = pic_name.substring(pic_name.lastIndexOf("."));
            String newFileName = model.getStr("goods_number") + "_" + model.getStr("pic_type") + "_" + newIndex + suffix;
            File file = new File(webRoot + "/" + model.getStr("url"));
            file.renameTo(new File(webRoot + "/" + "File/images/goods" + "/" + newFileName));
            model.set("url", "File/images/goods" + "/" + newFileName);
            model.set("pic_name", newFileName);
        }
        if (model.update()) {
            toDwzJson(Constant.STATUS_CODE_OK, "商品图片修改完成！", goodsPictureViewNavTabId, "", "closeCurrent", "");
        } else {
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 上传商品图片处理
     */
    public void goodsPictureUpload() {
        try {
            UploadFile file = getFile("goods_picture", "images/goods", maxPostSize);
            String suffix = file.getFileName().substring(file.getFileName().lastIndexOf(".") + 1, file.getFileName().length()).toLowerCase();
            if (!suffix.equals("jpg") && !suffix.equals("png") && !suffix.equals("bmp")) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "只支持以jpg,png,bmp为后缀的图片文件！", "", "", "", "");
            }

            String goods_number = getPara("goods_number");
            String picture_type = getPara("picture_type");

            if (null == goods_number || 0 == goods_number.trim().length()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
                return;
            }
            if (null == picture_type || 0 == picture_type.trim().length()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
                return;
            }

            int newIndex = T_Goods_Picture.dao.getPicNewIndexByPicType(picture_type);
            String fileName = goods_number + "_" + picture_type + "_" + newIndex + "." + suffix;
            file.getFile().renameTo(new File(webRoot + "/" + "File/images/goods" + "/" + fileName));

            boolean result = new T_Goods_Picture().set("goods_number", goods_number).set("url", "File/images/goods" + "/" + fileName).set("pic_name", fileName)
                    .set("pic_type", picture_type).set("pic_index", newIndex).save();

            if (result) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品图片上传完成！", goodsPictureViewNavTabId, "", "closeCurrent", "");
            }

        } catch (Exception e) {
            log.error("上传图片出错，请检查后再提交！", e);
            render(new JsonRender("{\"err\":\"上传图片出错，请检查后再提交！\",\"msg\":\"\"}").forIE());
        }
    }

    /**
     * 商品图片删除处理
     */
    public void goodsPictureDelete() {
        Integer id;
        try {
            id = getParaToInt("id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods_Picture model = T_Goods_Picture.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品图片不存在！", "", "", "", "");
            return;
        }
        model.set("is_delete", "1");
        try {
            if (model.update()) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品图片删除完成！", goodsPictureViewNavTabId, "", "", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 进入特殊图片浏览页面
     */
    public void specialPictureViewip() {
        List<T_Special_Picture> pictureList = T_Special_Picture.dao.list();

        setAttr("pictureList", pictureList);
        render("specialPictureView.jsp");
    }

    /**
     * 进入上传特殊图片页面
     */
    public void specialPictureUploadip() {
        List<T_Goods> goodsList = T_Goods.dao.list();

        setAttr("goodsList", goodsList);
        render("specialPictureUpload.jsp");
    }

    /**
     * 特殊图片修改页面
     */
    public void specialPictureUpdateip() {
        Integer id;
        try {
            id = getParaToInt("id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Special_Picture model = T_Special_Picture.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，特殊图片不存在！", "", "", "", "");
            return;
        }

        List<T_Goods> goodsList = T_Goods.dao.list();
        setAttr("goodsList", goodsList);
        setAttr("t_Special_Picture", model);
        render("specialPictureUpdate.jsp");
    }

    /**
     * 特殊图片修改处理
     */
    public void specialPictureUpdate() {
        Integer id;
        try {
            id = getParaToInt("t_Special_Picture.id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        String goods_number = getPara("goods_number");
        if (null == goods_number || 0 == goods_number.trim().length()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        final T_Special_Picture model = T_Special_Picture.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，特殊图片不存在！", "", "", "", "");
            return;
        }

        if(!model.getStr("goods_number").equals(goods_number)) {
            model.set("goods_number", goods_number);
        }

        Integer newIndex = model.getInt("pic_index");
        if (!model.getStr("pic_type").equals(getPara("t_Special_Picture.pic_type"))) {
            newIndex = T_Special_Picture.dao.getPicNewIndexByPicType(getPara("t_Special_Picture.pic_type"));
            model.set("pic_type", getPara("t_Special_Picture.pic_type")).set("pic_index", newIndex);
        }
        //更改本地文件名，url，pic_name
        String pic_name = model.getStr("pic_name");
        String suffix = pic_name.substring(pic_name.lastIndexOf("."));
        String newFileName = goods_number + "_" + model.getStr("pic_type") + "_" + newIndex + suffix;

        if(T_Special_Picture.dao.hasSameUrl("File/images/special" + "/" + newFileName)) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "存在相同名字的图片！", "", "", "", "");
            return;
        }

        File file = new File(webRoot + "/" + model.getStr("url"));
        file.renameTo(new File(webRoot + "/" + "File/images/special" + "/" + newFileName));
        model.set("url", "File/images/special" + "/" + newFileName);
        model.set("pic_name", newFileName);

        if (model.update()) {
            toDwzJson(Constant.STATUS_CODE_OK, "特殊图片修改完成！", specialPictureViewNavTabId, "", "closeCurrent", "");
        } else {
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 上传特殊图片处理
     */
    public void specialPictureUpload() {
        try {
            UploadFile file = getFile("special_picture", "images/special", maxPostSize);
            String suffix = file.getFileName().substring(file.getFileName().lastIndexOf(".") + 1, file.getFileName().length()).toLowerCase();
            if (!suffix.equals("jpg") && !suffix.equals("png") && !suffix.equals("bmp")) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "只支持以jpg,png,bmp为后缀的图片文件！", "", "", "", "");
            }

            String goods_number = getPara("goods_number");
            String picture_type = getPara("picture_type");

            if (null == goods_number || 0 == goods_number.trim().length()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
                return;
            }
            if (null == picture_type || 0 == picture_type.trim().length()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
                return;
            }

            int newIndex = T_Special_Picture.dao.getPicNewIndexByPicType(picture_type);
            String fileName = goods_number + "_" + picture_type + "_" + newIndex + "." + suffix;
            file.getFile().renameTo(new File(webRoot + "/" + "File/images/special" + "/" + fileName));

            boolean result = new T_Special_Picture().set("goods_number", goods_number).set("url", "File/images/special" + "/" + fileName).set("pic_name", fileName)
                    .set("pic_type", picture_type).set("pic_index", newIndex).save();

            if (result) {
                toDwzJson(Constant.STATUS_CODE_OK, "特殊图片上传完成！", specialPictureViewNavTabId, "", "closeCurrent", "");
            }

        } catch (Exception e) {
            log.error("上传图片出错，请检查后再提交！", e);
            render(new JsonRender("{\"err\":\"上传图片出错，请检查后再提交！\",\"msg\":\"\"}").forIE());
        }
    }

    /**
     * 特殊图片删除处理
     */
    public void specialPictureDelete() {
        Integer id;
        try {
            id = getParaToInt("id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Special_Picture model = T_Special_Picture.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，特殊图片不存在！", "", "", "", "");
            return;
        }
        model.set("is_delete", "1");
        try {
            if (model.update()) {
                toDwzJson(Constant.STATUS_CODE_OK, "特殊图片删除完成！", specialPictureViewNavTabId, "", "", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }
}
